package org.yuanqiframework.yuanqi.boot.sys.service;

import org.yuanqiframework.yuanqi.web.cache.service.RedisService;
import org.yuanqiframework.yuanqi.core.utils.captcha.ImageCaptcha;
import org.yuanqiframework.yuanqi.core.utils.captcha.ImageCaptchaUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.stereotype.Service;
import org.yuanqiframework.yuanqi.web.utils.SpringUtils;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class ImageCaptchaService {

    public ImageCaptcha make(Long timeout, int width, int height, int codeCount, int thickness) throws IOException {
        // 生成验证码
        ImageCaptcha captcha = ImageCaptchaUtils.captcha(width, height, codeCount, thickness);
        return save(captcha, timeout);
    }

    public ImageCaptcha make(Long timeout) throws IOException {
        // 生成验证码
        ImageCaptcha captcha = ImageCaptchaUtils.captcha();
        return save(captcha, timeout);
    }


    public Boolean check(String captchaKey, String captchaCode) {
        Boolean flag = false;
        try {
            RedisService redisService = SpringUtils.getBean(RedisService.class);
            String cacheCaptchaCode = redisService.getCacheObject(captchaKey);
            if (cacheCaptchaCode == null) {
                return false;
            }
            return captchaCode.equals(cacheCaptchaCode);
        } catch (BeansException e) {
            return ImageCaptchaUtils.testInMemory(captchaKey, captchaCode);
        }
    }

    private ImageCaptcha save(ImageCaptcha captcha, Long timeout) {
        // 保存验证码
        try {
            RedisService redisService = SpringUtils.getBean(RedisService.class);
            redisService.setCacheObject(captcha.getKey(), captcha.getCode(), timeout, TimeUnit.MINUTES);
        } catch (BeansException e) {
            log.warn("redis服务未启动，验证码将保存在内存中");
            ImageCaptchaUtils.cacheInMemory(captcha, timeout);
        }
        return captcha;
    }
}
